#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# This program is free software; you can redistribute it and/or modify  
# it under the terms of the GNU General Public License as published by  
# the Free Software Foundation; either version 2 of the License, or     
# (at your option) any later version.                                   
#                                                                         
# A copy of the license can be found in the license.txt file supplied   
# with this software or at: http://www.gnu.org/copyleft/gpl.html       
#


import time
import select
import threading

from help import logging


class   Routine(threading.Thread) :

    INTERVAL_CHECK_FINGER_TABLE = 10

    def __init__(self, node) :
        threading.Thread.__init__(self )

        self.node = node

        self.__serving = True
        self.__is_stop = threading.Event()

        self._countdown_check_finger_table = 0
        ## __init__()

    def run(self) :
        poll_interval = 0.5
        while self.__serving :
            r,w,e = select.select([],[],[],poll_interval)

            self._countdown_check_finger_table -= 1
            if self._countdown_check_finger_table <= 0 :
                self.checkFingerTable()
                self._countdown_check_finger_table = self.INTERVAL_CHECK_FINGER_TABLE
            # while

        self.__is_stop.set()
        ## run()

    def stop(self) :
        self.__serving = False
        self.__is_stop.wait()
        ## stop()

    #### --------------------------------------------------------- ####

    def checkFingerTable(self) :
        if self.node.when_finger_last_update > self.node.when_finger_last_check :
            ft_str = self.node.getPrettyPrintFingerTable()
            print ft_str
            self.node.when_finger_last_check = time.time()

        ## checkFingerTable()

    ## class Routine

